import { useCallback, useEffect, useState } from 'react';
import { Avatar, Button, Cell, Dialog, Empty, Input, NavBar, Radio, RadioGroup, Tabs } from '@nutui/nutui-react-taro';
import { View, Text } from '@tarojs/components';
import { useSelector } from 'react-redux';
import { IconFont } from '@nutui/icons-react-taro';
import { domain2 } from '@/constant';
import { fetchUser, getUser } from '@/utils/user';
import Taro, { useDidShow } from '@tarojs/taro';
import request from '@/utils/request';
import { waitForRender } from '@/utils/render';
import { IUser } from '@/types/user';

import './index.less';

// 优惠券类型选项
const couponOptions = [
  { text: '满10减5', value: 'full-10-reduce-5' },
  { text: '满20减10', value: 'full-20-reduce-10' },
  { text: '满30减15', value: 'full-30-reduce-15' },
  { text: '满1减7', value: 'full-1-reduce-7' },
];

// 有效期选项
const validityOptions = [
  { text: '1个月', value: '1-month' },
  { text: '3个月', value: '3-month' },
  { text: '6个月', value: '6-month' },
  { text: '1年', value: '1-year' },
];

// 用户卡片组件
const CardUser = ({ user, onSendCoupon }) => {
  return (
    <View className="user-card">
      <View className="user-content">
        <View className="user-box">
          <View className="icon-box">
              <Avatar
                size="48"
                className="nut-avatar"
                src={user.avatarUrl}
                shape="round"
              />
            {/* <Avatar
              size="48"
              icon={
                <IconFont
                  size={22}
                  fontClassName="icon"
                  color="#000"
                  classPrefix="go-farm"
                  name="avatar"
                />
              }
              shape="round"
            /> */}
          </View>
          <View className="user-item-wrapper">
            <View className="wrapper-title">
              <View>
                {user.nickName || '未设置'}
                {user.status === 'vip' && <Text className="admin-tag">管理员</Text>}
              </View>
            </View>
            <View className="user-info">
              <View>电话：{user.phone || '未设置'}</View>
              {user.community && (
                <View>
                  住址：{user.community} {user.building}栋 {user.unit}单元 {user.room}室
                </View>
              )}
            </View>
          </View>
        </View>
      </View>
      <View className="action-buttons">
        <Button 
          type="primary" 
          size="small" 
          onClick={() => onSendCoupon(user.id, user.nickname || '该用户')}
        >
          发优惠券
        </Button>
      </View>
    </View>
  );
};

// 空状态组件
const entryRender = (list: any[]) => {
  if (list.length) return list;
  return (
    <View className="empty-box">
      <Empty
        image={<img src={`${domain2}/subtract.png`} alt="" />}
        title="暂无用户"
        description="用户列表为空">
      </Empty>
    </View>
  );
};

export default function Index() {
  const barHeight = useSelector((state: any) => state.system.barHeight);
  const [tabvalue, setTabvalue] = useState<string | number>('0');
  const [loading, setLoading] = useState<boolean>(true);
  const [users, setUsers] = useState<IUser[]>([]);
  const [usersWithAddress, setUsersWithAddress] = useState<IUser[]>([]);
  const [user, setUser] = useState(getUser());
  
  // 优惠券表单状态
  const [showCouponForm, setShowCouponForm] = useState(false);
  const [selectedUserId, setSelectedUserId] = useState('');
  const [selectedUserName, setSelectedUserName] = useState('');
  const [couponName, setCouponName] = useState('满减优惠券');
  const [couponStrategy, setCouponStrategy] = useState('full-10-reduce-5');
  const [validityPeriod, setValidityPeriod] = useState('1-month');
  
  // 计算有效期范围
  const calculateValidityRange = (period) => {
    const startDate = new Date();
    const endDate = new Date();
    
    switch (period) {
      case '1-month':
        endDate.setMonth(endDate.getMonth() + 1);
        break;
      case '3-month':
        endDate.setMonth(endDate.getMonth() + 3);
        break;
      case '6-month':
        endDate.setMonth(endDate.getMonth() + 6);
        break;
      case '1-year':
        endDate.setFullYear(endDate.getFullYear() + 1);
        break;
      default:
        endDate.setMonth(endDate.getMonth() + 1);
    }
    
    // 格式化日期为 YYYY-MM-DD
    const formatDate = (date) => {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    };
    
    return `${formatDate(startDate)} to ${formatDate(endDate)}`;
  };

  // 获取所有用户
  const requestForUsers = useCallback(async () => {
    const users = await request
      .get<IUser[]>('/user/list', {})
      .finally(() => {
        waitForRender(() => setLoading(false));
      });
    setUsers(users || []);
    
    // 筛选有地址的用户
    const usersWithAddress = users.filter(
      user => user.community && user.building && user.unit && user.room
    );
    setUsersWithAddress(usersWithAddress);
  }, []);

  // 发送优惠券
  const handleSendCoupon = useCallback((userId: string, userName: string) => {
    setSelectedUserId(userId);
    setSelectedUserName(userName);
    setShowCouponForm(true);
  }, []);
  
  // 提交优惠券表单
  const submitCouponForm = useCallback(async () => {
    try {
      const canUseTime = calculateValidityRange(validityPeriod);
      
      const result: any = await request.post('/coupon/add', {
        userId: selectedUserId,
        name: couponName,
        strategy: couponStrategy,
        canUseTime
      });
      
      console.log('优惠券请求结果:', JSON.stringify(result));
      
      if (result) {
        Taro.showToast({
          title: `已成功发送优惠券`,
          icon: 'success',
        });
        setShowCouponForm(false);
      } else {
        Taro.showToast({
          title: `发送失败：请求返回为空`,
          icon: 'error',
        });
      }
    } catch (error: any) {
      console.error('优惠券发送错误:', error);
      Taro.showToast({
        title: `发送失败：${error?.message || '未知错误'}`,
        icon: 'error',
      });
    }
  }, [selectedUserId, selectedUserName, couponName, couponStrategy, validityPeriod]);

  useDidShow(() => {
    const _user = getUser();
    if (_user?.id) {
      fetchUser(_user.id).then((res) => setUser(res));
      requestForUsers();
    } else {
      setLoading(false);
    }
  });

  useEffect(() => {
    if (!user?.id) {
      setLoading(false);
      return;
    }
    requestForUsers();
  }, []);

  return (
    <View className="users">
      <Dialog id="dialog" />
      <View className="nav-bar">
        <View style={{ height: `${barHeight}px`, width: '100%' }}></View>
        <NavBar>用户列表</NavBar>
      </View>
      <Tabs
        value={tabvalue}
        onChange={(value) => {
          setTabvalue(value);
        }}>
        <Tabs.TabPane title="有地址用户">
          {entryRender(
            usersWithAddress.map((user) => (
              <CardUser 
                key={user.id} 
                user={user} 
                onSendCoupon={handleSendCoupon} 
              />
            ))
          )}
        </Tabs.TabPane>
        <Tabs.TabPane title="全部用户">
          {entryRender(
            users.map((user) => (
              <CardUser 
                key={user.id} 
                user={user} 
                onSendCoupon={handleSendCoupon} 
              />
            ))
          )}
        </Tabs.TabPane>
      </Tabs>
      
      {/* 优惠券表单对话框 */}
      <Dialog
        title="发送优惠券"
        visible={showCouponForm}
        onConfirm={submitCouponForm}
        onCancel={() => setShowCouponForm(false)}
      >
        <View className="coupon-form">
          <Cell title="优惠券名称">
            <Input 
              placeholder="请输入优惠券名称" 
              value={couponName}
              onChange={(val) => setCouponName(val)}
            />
          </Cell>
          <Cell title="优惠券类型">
            <RadioGroup value={couponStrategy} onChange={(value) => setCouponStrategy(value as string)}>
              {couponOptions.map((option) => (
                <Radio key={option.value} value={option.value}>
                  {option.text}
                </Radio>
              ))}
            </RadioGroup>
          </Cell>
          <Cell title="有效期">
            <RadioGroup value={validityPeriod} onChange={(value) => setValidityPeriod(value as string)}>
              {validityOptions.map((option) => (
                <Radio key={option.value} value={option.value}>
                  {option.text}
                </Radio>
              ))}
            </RadioGroup>
          </Cell>
        </View>
      </Dialog>
    </View>
  );
}
